package com.mico.xchange.huobi.dto.marketdata;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.BiConsumer;

public final class HuobiDepth {
 //TODO chenst
  private long id;
  private Date ts;
  private final SortedMap<BigDecimal, BigDecimal> bids;
  private final SortedMap<BigDecimal, BigDecimal> asks;

  public HuobiDepth(
      @JsonProperty("id") long id,
      @JsonProperty("ts") Date ts,
      @JsonProperty("bids") List<Object[]> bidsJson,
      @JsonProperty("asks") List<Object[]> asksJson) {
    this.id = id;
    this.ts = ts;

      BiConsumer<Object[], Map<BigDecimal, BigDecimal>> entryProcessor =
              (obj, col) -> {
                  BigDecimal price = new BigDecimal(obj[0].toString());
                  BigDecimal qty = new BigDecimal(obj[1].toString());
                  col.put(price, qty);
              };
      TreeMap<BigDecimal, BigDecimal> bids = new TreeMap<>((k1, k2) -> -k1.compareTo(k2));
      TreeMap<BigDecimal, BigDecimal> asks = new TreeMap<>();

      bidsJson.stream().forEach(e -> entryProcessor.accept(e, bids));
      asksJson.stream().forEach(e -> entryProcessor.accept(e, asks));

      this.bids = Collections.unmodifiableSortedMap(bids);
      this.asks = Collections.unmodifiableSortedMap(asks);

     /*for(JSONArray array : bids){
          BigDecimal[] a = new BigDecimal[2];
          a[0] = new BigDecimal(array.get(0).toString());
          a[1] = new BigDecimal(array.get(1).toString());
          this.bids.add(a);
      }
      for(JSONArray array : asks){
          BigDecimal[] a = new BigDecimal[2];
          a[0] = new BigDecimal(array.get(0).toString());
          a[1] = new BigDecimal(array.get(1).toString());
          this.asks.add(a);
      }*/
  }

  public long getId() {
    return id;
  }

  public Date getTs() {
    return ts;
  }

  public SortedMap<BigDecimal, BigDecimal> getBids() {
    return bids;
  }

  public SortedMap<BigDecimal, BigDecimal> getAsks() {
    return asks;
  }

  public void setTs(Date ts) {
    this.ts = ts;
  }

  @Override
  public String toString() {
    return "HuobiDepth{" +
            "id=" + id +
            ", ts=" + ts +
            ", bids=" + bids +
            ", asks=" + asks +
            '}';
  }
}
